package com.sjyl.kaoshitong.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.activities.FilterActivity;
import com.sjyl.kaoshitong.activities.MyDocumentFileListActivity;
import com.sjyl.kaoshitong.adapter.MyDocumentFolderRecyclerViewAdapter;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.CatalogItem;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import tr.xip.errorview.ErrorView;

/**
 * Created by ChangerLow on 15/4/25.
 * Email: changerlow@qq.com
 */
public class MyDocumentFolderFragment extends Fragment implements MyDocumentFolderRecyclerViewAdapter.MyDocumentFileViewHolder.MyOnItemClickListener {
    private static final String TAG = "MyDocumentFragment";
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private MyDocumentFolderRecyclerViewAdapter recyclerViewAdapter;
    private List<CatalogItem> dataList;
    private LinearLayout refreshView;
    private ErrorView errorView;
    private LinearLayout emptyView;
    private RelativeLayout contentView;
    private FloatingActionButton fab;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();
    private String pid;
    private String departId;

    private enum ErrorType {
        NO_DATA, RESPONSE_ERROR
    }
    //http://www.yiyihulian.com:9080/kstInter/?funName=getDataCatalogList&departId=1&userId=1&keyWord=a1acbe25170414e8bc00b2b2aeabdc2d


    public static MyDocumentFolderFragment newInstance(String param) {
        MyDocumentFolderFragment fragment = new MyDocumentFolderFragment();
        Bundle bundle = new Bundle();
        bundle.putString("pid", param);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
        Bundle bundle = getArguments();
        pid = bundle.getString("pid");
        if (TextUtils.isEmpty(pid)) {
            pid = Hawk.get(PreferencesKeyUtil.KEY_CURRENT_SELECTED_ID);
        }
        departId = Hawk.get(PreferencesKeyUtil.KEY_DEPART_ID, "1");
        pid="249";
        departId = "9";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my_document_folder_layout, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.color_primary, R.color.color_primary_dark);
        refreshView = (LinearLayout) rootView.findViewById(R.id.refresh_layout);
        contentView = (RelativeLayout)rootView.findViewById(R.id.content_layout);
        errorView = (ErrorView) rootView.findViewById(R.id.error_view);
        emptyView = (LinearLayout)rootView.findViewById(R.id.emptyview);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        dataList = new ArrayList<>();
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerViewAdapter = new MyDocumentFolderRecyclerViewAdapter(dataList);
        recyclerView.setAdapter(recyclerViewAdapter);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                recyclerViewAdapter.notifyDataSetChanged();
//                swipeRefreshLayout.setRefreshing(false);
            }
        });
        recyclerViewAdapter.setOnItemClickListener(this);
        fab = (android.support.design.widget.FloatingActionButton) rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FilterActivity.class);
                getActivity().startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.do_nothing);
            }
        });
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        showProgress();
        getData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void OnItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), MyDocumentFileListActivity.class);
        intent.putExtra("pid", dataList.get(position).getId());
        intent.putExtra("title", dataList.get(position).getCatalog_name());
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

    }

    private void getData() {
        RequestBody body = new FormEncodingBuilder().add("funName", "getDataCatalogList").add("departId", departId).add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID, "")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).add("pid", pid).build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showErrorview();
                        return;
                    }
                });

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<CatalogItem>>() {
                }.getType();
                final ApiResponse<CatalogItem> apiResponse = gson.fromJson(body, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!apiResponse.getRecode().equals("2000")) {
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.get_data_error));
                            showErrorview();
                            return;
                        } else {
                            Recontent<CatalogItem> recontent = apiResponse.getRecontent();
                            if (apiResponse.getRecontent() == null) {
                                showEmptyView();
                                return;
                            }
                            List<CatalogItem> list = recontent.getRelist();
                            if (list.size() == 0 ){
                                showEmptyView();
                                return;
                            }

                            Logger.d(TAG, "=========recode:" + " relist size:" + list.size());
                            dataList.addAll(list);
                            recyclerViewAdapter.notifyDataSetChanged();
                            showContent();
                        }
                    }
                });
            }
        });
    }


    private void showProgress() {
        refreshView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);
        contentView.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
    }

    private void showContent() {
        refreshView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        contentView.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }

    private void showErrorview() {
        refreshView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        contentView.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
    }

    private void showEmptyView(){
        refreshView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        contentView.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
    }

}
